/**
 * Shopro-request
 * @description api模块管理，loading配置，请求拦截，错误处理
 */


import { baseUrl, apiPath, HEADERPARAMS, TOKENNAME, HEADER } from '@/mall/config';
import $store from '@/mall/store';
import $platform from '@/mall/platform';
import { showAuthModal } from '@/mall/hooks/useModal';
// import {
//   toLogin,
//   checkLogin
// } from '../libs/login';



/**
 * 发送请求
 */
function baseRequest(url, method, data, {
  noAuth = false,
  noVerify = false
}, params) {
  let header = HEADER
  if (params != undefined) {
    header = HEADERPARAMS;
  }
  if (!noAuth && !$store('user').isLogin) {
    //登录过期自动登录
    showAuthModal();
    return Promise.reject();
  }
  const token = uni.getStorageSync('token');
  if (token) header[TOKENNAME] = token;
  return new Promise((reslove, reject) => {
    uni.request({
      url: `${baseUrl}${apiPath}${url}`,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
        if (noVerify)
          reslove(res.data, res);
        else if (res.data.code == 200)
          reslove(res.data, res);
        else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
          $store('user').logout(true)
          reject(res.data);
        } else
          reject(res.data.message || '系统错误');
      },
      fail: (msg) => {
        reject('请求失败');
      }
    })
  });
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = ({ url, data, opt, params }) => baseRequest(url, method, data, opt || {}, params)
});



export default request;
